/**
 * Licensed under the Apache License Version 2.0.
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.interknit.knitter.cg.cfg;

import java.util.ArrayList;
import java.util.List;

import org.apache.tools.ant.DirectoryScanner;
import org.jdom.Element;

public class ClasspathEl
{
	private final List<DirEl> directories = new ArrayList<DirEl>();
	private final List<FileEl> files = new ArrayList<FileEl>();

	ClasspathEl()
	{
		;
	}

	public ClasspathEl(Element el)
	{
		if(el == null) return;

		for(Element dirEl : (List<Element>) el.getChildren("dir"))
			directories.add(new DirEl(dirEl));

		for(Element fileEl : (List<Element>) el.getChildren("file"))
			files.add(new FileEl(fileEl));
	}

	public List<DirEl> getDirectories()
	{
		return directories;
	}

	public List<FileEl> getFiles()
	{
		return files;
	}

	@Override
	public String toString()
	{
		String val = "<classpath>" + "\n";

		for(DirEl dir : directories)
			val = val + dir.toString();
		for(FileEl file : files)
			val = val + file.toString();

		return val + "</classpath>";
	}

	public String[] getClasspathEntries()
	{
		List<String> entries = new ArrayList<String>();

		for(DirEl dir : directories)
		{
			entries.add(dir.getPath());

			String includeFilter = dir.getIncludes();
			if(includeFilter != null && ! "".equals(includeFilter))
			{
				DirectoryScanner ds = new DirectoryScanner();
				ds.setBasedir(dir.getPath());
				ds.setIncludes(dir.getIncludes().split(","));
				ds.scan();

				String[] farr = ds.getIncludedFiles();

				for(int i = 0; i < farr.length; i++)
					entries.add(ds.getBasedir() + "/" + farr[i]);
			}
		}

		for(FileEl file : files) entries.add(file.getPath());

		return entries.toArray(new String[entries.size()]);
	}
}
